document.addEventListener('DOMContentLoaded', () => {
    // 游戏常量
    const COLS = 10;
    const ROWS = 20;
    const BLOCK_SIZE = 30;
    const COLORS = [
        'cyan', 'blue', 'orange', 'yellow', 'green', 'purple', 'red'
    ];
    
    // 方块形状定义
    const SHAPES = [
        [[1, 1, 1, 1]],                         // I
        [[1, 1, 1], [0, 1, 0]],                 // T
        [[1, 1, 1], [1, 0, 0]],                 // L
        [[1, 1, 1], [0, 0, 1]],                 // J
        [[1, 1], [1, 1]],                       // O
        [[0, 1, 1], [1, 1, 0]],                 // S
        [[1, 1, 0], [0, 1, 1]]                  // Z
    ];
    
    // 游戏变量
    let canvas = document.getElementById('tetris');
    let ctx = canvas.getContext('2d');
    let nextPieceCanvas = document.createElement('canvas');
    let nextPieceCtx = nextPieceCanvas.getContext('2d');
    let scoreElement = document.getElementById('score');
    let levelElement = document.getElementById('level');
    let linesElement = document.getElementById('lines');
    let timeElement = document.getElementById('time');
    let nextPieceDisplay = document.getElementById('next-piece-display');
    
    // 设置下一个方块预览画布
    nextPieceCanvas.width = 40;
    nextPieceCanvas.height = 40;
    nextPieceDisplay.appendChild(nextPieceCanvas);
    
    // 游戏状态
    let board = Array(ROWS).fill().map(() => Array(COLS).fill(0));
    let score = 0;
    let level = 1;
    let lines = 0;
    let gameOver = false;
    let isPaused = false;
    let dropStart = Date.now();
    let piece;
    let nextPiece;
    let gameStartTime = 0;
    let gameTime = 0;
    let timerId;
    
    // 调整画布大小
    function resizeCanvas() {
        if (window.innerWidth <= 768) {
            canvas.width = 200;
            canvas.height = 400;
        } else {
            canvas.width = 300;
            canvas.height = 600;
        }
        drawBoard();
    }
    
    // 初始化游戏
    function init() {
        resizeCanvas();
        generatePiece();
        generateNextPiece();
        draw();
        
        // 添加事件监听器
        document.addEventListener('keydown', handleKeyPress);
        
        // 移动端控制 - 复古游戏手柄
        document.getElementById('left-btn').addEventListener('click', () => movePiece(-1, 0));
        document.getElementById('right-btn').addEventListener('click', () => movePiece(1, 0));
        document.getElementById('down-btn').addEventListener('click', () => movePiece(0, 1));
        document.getElementById('up-btn').addEventListener('click', rotatePiece); // 上键也可以旋转
        document.getElementById('rotate-btn').addEventListener('click', rotatePiece); // A按钮旋转
        document.getElementById('drop-btn').addEventListener('click', dropPiece); // B按钮快速下落
        
        // 游戏控制按钮
        document.getElementById('start-btn').addEventListener('click', startGame);
        document.getElementById('pause-btn').addEventListener('click', togglePause);
        document.getElementById('restart-btn').addEventListener('click', restartGame);
        
        // 响应式设计
        window.addEventListener('resize', resizeCanvas);
    }
    
    // 开始游戏
    function startGame() {
        if (gameOver) {
            restartGame();
            return;
        }
        
        if (isPaused) {
            togglePause();
        } else {
            // 开始计时
            gameStartTime = Date.now() - gameTime;
            startTimer();
        }
        
        // 开始游戏循环
        requestAnimationFrame(gameLoop);
    }
    
    // 开始计时器
    function startTimer() {
        // 清除之前的计时器
        if (timerId) {
            clearInterval(timerId);
        }
        
        // 每秒更新一次时间
        timerId = setInterval(() => {
            if (!isPaused && !gameOver) {
                gameTime = Date.now() - gameStartTime;
                updateTime();
            }
        }, 1000);
    }
    
    // 更新时间显示
    function updateTime() {
        const totalSeconds = Math.floor(gameTime / 1000);
        const minutes = Math.floor(totalSeconds / 60);
        const seconds = totalSeconds % 60;
        timeElement.textContent = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
    }
    
    // 暂停/继续游戏
    function togglePause() {
        isPaused = !isPaused;
        document.getElementById('pause-btn').textContent = isPaused ? '继续' : '暂停';
        
        if (!isPaused) {
            // 继续游戏时，更新开始时间以保持计时准确
            gameStartTime = Date.now() - gameTime;
            dropStart = Date.now();
            requestAnimationFrame(gameLoop);
        }
    }
    
    // 重新开始游戏
    function restartGame() {
        board = Array(ROWS).fill().map(() => Array(COLS).fill(0));
        score = 0;
        level = 1;
        lines = 0;
        gameOver = false;
        isPaused = false;
        
        // 重置游戏时间
        gameTime = 0;
        gameStartTime = Date.now();
        updateTime();
        startTimer();
        
        updateScore();
        generatePiece();
        generateNextPiece();
        
        document.getElementById('pause-btn').textContent = '暂停';
        
        dropStart = Date.now();
        requestAnimationFrame(gameLoop);
    }
    
    // 游戏主循环
    function gameLoop(timestamp) {
        if (gameOver || isPaused) return;
        
        let now = Date.now();
        let deltaTime = now - dropStart;
        
        if (deltaTime > getDropInterval()) {
            movePiece(0, 1);
            dropStart = now;
        }
        
        draw();
        requestAnimationFrame(gameLoop);
    }
    
    // 根据等级获取下落间隔时间
    function getDropInterval() {
        return 1000 - (level - 1) * 100 > 100 ? 1000 - (level - 1) * 100 : 100;
    }
    
    // 生成新方块
    function generatePiece() {
        if (nextPiece) {
            piece = nextPiece;
            generateNextPiece();
        } else {
            let shapeIndex = Math.floor(Math.random() * SHAPES.length);
            piece = {
                shape: SHAPES[shapeIndex],
                color: COLORS[shapeIndex],
                x: Math.floor(COLS / 2) - Math.floor(SHAPES[shapeIndex][0].length / 2),
                y: 0
            };
        }
        
        // 检查游戏是否结束
        if (collision(0, 0)) {
            gameOver = true;
            // 停止计时器
            if (timerId) {
                clearInterval(timerId);
            }
            alert('游戏结束！你的分数是: ' + score + '，游戏时间: ' + timeElement.textContent);
        }
    }
    
    // 生成下一个方块
    function generateNextPiece() {
        let shapeIndex = Math.floor(Math.random() * SHAPES.length);
        nextPiece = {
            shape: SHAPES[shapeIndex],
            color: COLORS[shapeIndex],
            x: Math.floor(COLS / 2) - Math.floor(SHAPES[shapeIndex][0].length / 2),
            y: 0
        };
        
        drawNextPiece();
    }
    
    // 绘制下一个方块预览
    function drawNextPiece() {
        nextPieceCtx.clearRect(0, 0, nextPieceCanvas.width, nextPieceCanvas.height);
        nextPieceCtx.fillStyle = '#222';
        nextPieceCtx.fillRect(0, 0, nextPieceCanvas.width, nextPieceCanvas.height);
        
        let blockSize = 8;
        let offsetX = (nextPieceCanvas.width - nextPiece.shape[0].length * blockSize) / 2;
        let offsetY = (nextPieceCanvas.height - nextPiece.shape.length * blockSize) / 2;
        
        nextPiece.shape.forEach((row, y) => {
            row.forEach((value, x) => {
                if (value) {
                    drawBlock(
                        nextPieceCtx,
                        x * blockSize + offsetX,
                        y * blockSize + offsetY,
                        blockSize,
                        nextPiece.color
                    );
                }
            });
        });
    }
    
    // 绘制方块
    function drawBlock(context, x, y, size, color) {
        context.fillStyle = color;
        context.fillRect(x, y, size, size);
        
        context.strokeStyle = 'black';
        context.strokeRect(x, y, size, size);
        
        // 添加高光效果
        context.fillStyle = 'rgba(255, 255, 255, 0.2)';
        context.fillRect(x, y, size, size / 4);
        context.fillRect(x, y, size / 4, size);
    }
    
    // 绘制游戏板
    function drawBoard() {
        const blockWidth = canvas.width / COLS;
        const blockHeight = canvas.height / ROWS;
        
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.fillStyle = '#000';
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        
        board.forEach((row, y) => {
            row.forEach((value, x) => {
                if (value) {
                    drawBlock(
                        ctx,
                        x * blockWidth,
                        y * blockHeight,
                        blockWidth,
                        COLORS[value - 1]
                    );
                }
            });
        });
    }
    
    // 绘制当前方块
    function drawPiece() {
        const blockWidth = canvas.width / COLS;
        const blockHeight = canvas.height / ROWS;
        
        piece.shape.forEach((row, y) => {
            row.forEach((value, x) => {
                if (value) {
                    drawBlock(
                        ctx,
                        (piece.x + x) * blockWidth,
                        (piece.y + y) * blockHeight,
                        blockWidth,
                        piece.color
                    );
                }
            });
        });
    }
    
    // 绘制游戏
    function draw() {
        drawBoard();
        drawPiece();
    }
    
    // 检测碰撞
    function collision(offsetX, offsetY, rotatedShape = piece.shape) {
        for (let y = 0; y < rotatedShape.length; y++) {
            for (let x = 0; x < rotatedShape[y].length; x++) {
                if (rotatedShape[y][x]) {
                    let newX = piece.x + x + offsetX;
                    let newY = piece.y + y + offsetY;
                    
                    if (newX < 0 || newX >= COLS || newY >= ROWS) {
                        return true;
                    }
                    
                    if (newY >= 0 && board[newY][newX]) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
    
    // 移动方块
    function movePiece(offsetX, offsetY) {
        if (gameOver || isPaused) return;
        
        if (!collision(offsetX, offsetY)) {
            piece.x += offsetX;
            piece.y += offsetY;
        } else if (offsetY > 0) {
            // 方块落地
            lockPiece();
            clearLines();
            generatePiece();
        }
        
        draw();
    }
    
    // 旋转方块
    function rotatePiece() {
        if (gameOver || isPaused) return;
        
        let rotatedShape = [];
        for (let i = 0; i < piece.shape[0].length; i++) {
            let row = [];
            for (let j = piece.shape.length - 1; j >= 0; j--) {
                row.push(piece.shape[j][i]);
            }
            rotatedShape.push(row);
        }
        
        if (!collision(0, 0, rotatedShape)) {
            piece.shape = rotatedShape;
        }
        
        draw();
    }
    
    // 快速下落
    function dropPiece() {
        if (gameOver || isPaused) return;
        
        while (!collision(0, 1)) {
            piece.y++;
        }
        
        lockPiece();
        clearLines();
        generatePiece();
        draw();
    }
    
    // 锁定方块
    function lockPiece() {
        piece.shape.forEach((row, y) => {
            row.forEach((value, x) => {
                if (value) {
                    let boardY = piece.y + y;
                    if (boardY >= 0) {
                        board[boardY][piece.x + x] = COLORS.indexOf(piece.color) + 1;
                    }
                }
            });
        });
    }
    
    // 清除完整的行
    function clearLines() {
        let linesCleared = 0;
        
        for (let y = ROWS - 1; y >= 0; y--) {
            let isLineComplete = true;
            
            for (let x = 0; x < COLS; x++) {
                if (!board[y][x]) {
                    isLineComplete = false;
                    break;
                }
            }
            
            if (isLineComplete) {
                linesCleared++;
                
                // 将上面的行下移
                for (let yy = y; yy > 0; yy--) {
                    for (let x = 0; x < COLS; x++) {
                        board[yy][x] = board[yy - 1][x];
                    }
                }
                
                // 清空顶部行
                for (let x = 0; x < COLS; x++) {
                    board[0][x] = 0;
                }
                
                // 因为行下移了，需要重新检查当前行
                y++;
            }
        }
        
        if (linesCleared > 0) {
            // 更新分数
            lines += linesCleared;
            score += calculateScore(linesCleared);
            
            // 更新等级
            level = Math.floor(lines / 10) + 1;
            
            updateScore();
        }
    }
    
    // 计算分数
    function calculateScore(linesCleared) {
        const points = [40, 100, 300, 1200]; // 1, 2, 3, 4行的分数
        return points[linesCleared - 1] * level;
    }
    
    // 更新分数显示
    function updateScore() {
        scoreElement.textContent = score;
        levelElement.textContent = level;
        linesElement.textContent = lines;
    }
    
    // 处理键盘输入
    function handleKeyPress(event) {
        if (gameOver) return;
        
        switch (event.keyCode) {
            case 37: // 左箭头
                movePiece(-1, 0);
                break;
            case 39: // 右箭头
                movePiece(1, 0);
                break;
            case 40: // 下箭头
                movePiece(0, 1);
                break;
            case 38: // 上箭头
                rotatePiece();
                break;
            case 32: // 空格键
                dropPiece();
                break;
            case 80: // P键
                togglePause();
                break;
        }
    }
    
    // 初始化游戏
    init();
});